#include "precompile.h"

#include "DisplayWorkflow.h"
#include "Layout.h"

DisplayWorkflow::DisplayWorkflow(void)
{
}

DisplayWorkflow::~DisplayWorkflow(void)
{
}

Graphics* DisplayWorkflow::GetGraphics() const
{
	return m_graphics;
}

void DisplayWorkflow::Prepare(PresentationContext& context)
{
	m_graphics = CreateGraphics(displayGraphics);
	DisplayPresentationContext& displayContext = (DisplayPresentationContext&)context;
	DeviceSurface surface(displayContext.GetContext());
	GetGraphics()->Create(&surface,displayContext.GetScale());
}

void DisplayWorkflow::RunPresentation(PresentationContext& context)
{
	DisplayPresentationContext& displayContext = (DisplayPresentationContext&)context;
	Size clientSize = displayContext.GetSize();
	DeviceSurface surface(displayContext.GetContext());
	GetGraphics()->Create(&surface,displayContext.GetScale());

	//draw background
	Point ptworld= GetGraphics()->CoordinateDeviceToWorld(Point(clientSize.cx,clientSize.cy));
	clientSize = Size(ptworld.x,ptworld.y);
	GetGraphics()->FillRectangle(SolidBrush(Color::White),Point(0,0),clientSize);

	//call pages presentation
	objectarray pages;
	sys::ServiceInterfacePtr<IHierarchyService> pIFHierarchyService(HIERARCHY_SERVICE);
	if (pIFHierarchyService->GetPages(displayContext.GetTarget(),pages))
	{
		//layout pages
		sys::InterfacePtr<IPage> pIFPage(pages[0]);
		Size pagesize(m_graphics->UnitMMtoLine(pIFPage->getPageWidth()),
								 m_graphics->UnitMMtoLine(pIFPage->getPageHeight()));
		PageLayout layout(clientSize,pagesize,pages.size(),Point(0,0));
		layout.Layout();

		const PageLayoutInfo& layoutInfo = layout.GetResult();
		for (int i  =0; i < layoutInfo.pages.size() && i < pages.size(); ++i)
		{
			const PageLayoutEntry& entry = layoutInfo.pages[i];
			const Point& viewpoint = entry.viewpoint;

			const Matrix& matrix = m_graphics->GetTransform();
			m_graphics->TranslateTransform(viewpoint.x,viewpoint.y);

			context.SetTarget(pages[i]);
			getPresentationRuntime()->RunPresentation(GetGraphics(),context);

		//	m_graphics->ResetTransform();
			sys::ServiceInterfacePtr<IHierarchyService> pIFHierarchyService(HIERARCHY_SERVICE);
			objectarray items;
			pIFHierarchyService->GetItems(pages[i],items);
			for (uint32 i = 0; i < items.size(); ++i)
			{
				context.SetTarget(items[i]);
				GetPresentationRuntime()->RunPresentation(GetGraphics(),context);
			}

			//draw trackers

			m_graphics->SetTransform(matrix);
		}
	}
}

void DisplayWorkflow::FinishPresentation(PresentationContext& context)
{
	context;
}